package com.nlelpct.excel;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Copyright @2018 nlelpct.
 *
 * @author: 黄磊
 * date:  2020/2/21  11:11
 * use to：统一导出下载excel文件
 * modify：
 */
public class ExcelUtils {

    // 下载excel文件
    public static void exportExcel(ExcelExportData excelExportData) throws IOException {
        // 居中对齐
        WriteCellStyle headerStyle = new WriteCellStyle();
        headerStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteCellStyle contentStyle = new WriteCellStyle();
        contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        HorizontalCellStyleStrategy strategy = new HorizontalCellStyleStrategy(headerStyle, contentStyle);
        EasyExcel.write(getOutputStream(excelExportData.getResponse(), excelExportData.getFileName()),
                excelExportData.getClazz()).excelType(ExcelTypeEnum.XLSX)
                .sheet(excelExportData.getSheetName()).registerWriteHandler(strategy)
                .doWrite(excelExportData.getList());
    }


    /**
     * 时    间: 2020/2/21 12:02
     * 方法描述：构建response返回参数
     * 返回类型：
     * 修改内容：（若修改了请注明修改人，修改时间，修改内容）
     */
    private static OutputStream getOutputStream(HttpServletResponse response, String fileName) throws IOException {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        return response.getOutputStream();
    }
}
